﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    internal class ClientSocket
    {
        private static int CLIENT_BEGIN_ID = 1;
        public Socket socketClient;
        public int clientID;
        public bool Connected => this.socketClient.Connected;
        public ClientSocket(Socket clientSocket)
        {
            this.clientID = CLIENT_BEGIN_ID;
            this.socketClient = clientSocket;
            CLIENT_BEGIN_ID++;
        }
        public void Close()
        {
            if (socketClient != null)
            {
                socketClient.Shutdown(SocketShutdown.Both);
                socketClient.Close();
            }
        }
        public void Send(string data)
        {
            if (socketClient != null)
            {
                socketClient.Send(Encoding.UTF8.GetBytes(data));
            }
        }
        public void Receive()
        {
            if(socketClient == null) 
                return;
            
            if(socketClient.Available > 0 )
            {
                byte[] buffer = new byte[1024];
                int receiveNum = socketClient.Receive(buffer);
                ThreadPool.QueueUserWorkItem(MsgHandle, Encoding.UTF8.GetString(buffer, 0, receiveNum));
            }
        }
        private void MsgHandle(object obj)
        {
            string str=obj as string;
            Console.WriteLine("收到客户端{0}发来的消息：{1}",this.socketClient.RemoteEndPoint,str);
        }
    }
}
